package com.mjk.common.core.rmq.conf;


import com.mjk.common.core.rmq.EventBus;
import com.mjk.common.core.rmq.annotation.Subscribe;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Method;

public class SubscribeAnnotationBeanFactory implements BeanPostProcessor, BeeApplicationListener {
	
	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		EventBus.startSubscribe();
	}	

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		if (AopUtils.isAopProxy(bean)) {
			clazz = AopUtils.getTargetClass(bean);
		}
		boolean register = false;
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			String name = method.getName();
			try {
				Subscribe sub = method.getAnnotation(Subscribe.class);
				if (sub != null) {
					register = true;
					break;
				}
			} catch (Exception e) {
				throw new BeanInitializationException("Failed to register event subscriber at method " + name
						+ " in class " + bean.getClass().getName(), e);
			}
		}
		if (register) {
			EventBus.registerListener(bean);
			//logger.debug("register listener[{}],status[{}]", bean.getClass().getName(), result);
		}
		return bean;
	}

}
